import React, { useRef, useEffect, useState } from 'react';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { getList, setStatus, del, delAll } from '@/services/admin/information/personnel/api';
import { getDepartmentList } from '@/services/admin/information/department/api';
import { Switch, Space, message } from 'antd';
import { PageContainer } from '@ant-design/pro-layout';
import { exportExcel } from '@/utils/ExportExcel';
import { getSort, setLsetData } from '@/utils/utils';
import FormIndex from './components/FormIndex';
import CDel from '@/components/common/CDel';
import CDelAll from '@/components/common/CDelAll';
const Index: React.FC = () => {
  const actionRef = useRef<ActionType>();
  let maps = {};
  const [departmentList, setDepartmentList] = useState<any>([]);
  const fetchApi = async () => {
    const res = await getDepartmentList();
    if (res.status == 20000) {
      const departmentData = [];
      for (let i = 0; i < res.data.length; i++) {
        departmentData[res.data[i].id] = {
          text: res.data[i].name,
          status: res.data[i].id,
        };
      }
      if (departmentData.length) await setDepartmentList({ ...departmentData });
    }
  };
  useEffect(() => {
    fetchApi();
  }, []);
  const columns: ProColumns<API.AdminPersonnelList>[] = [
    {
      title: '编号',
      dataIndex: 'id',
      hideInSearch: true,
      align: 'center',
      width: 80,
      fixed: true,
    },
    {
      title: '姓名',
      dataIndex: 'name',
      align: 'center',
      width: 100,
    },
    {
      title: '部门',
      dataIndex: 'department_to',
      hideInSearch: true,
      width: 120,
      align: 'center',
      render: (text, record) => [<span key={record.id}>{record.department_to?.name}</span>],
    },
    {
      title: '部门',
      dataIndex: 'department_id',
      valueType: 'select',
      fieldProps: {
        showSearch: true,
      },
      valueEnum: departmentList,
      hideInTable: true,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      valueType: 'select',
      width: 80,
      align: 'center',
      valueEnum: {
        0: {
          text: '女',
          status: '0',
        },
        1: {
          text: '男',
          status: '1',
        },
      },
    },
    {
      title: '民族',
      dataIndex: 'nation',
      align: 'center',
      width: 100,
    },
    {
      title: '出生日期',
      dataIndex: 'date_of_birth',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            'date_of_birth[0]': value[0],
            'date_of_birth[1]': value[1],
          };
        },
      },
    },
    {
      title: '出生日期',
      dataIndex: 'date_of_birth',
      valueType: 'date',
      sorter: true,
      hideInSearch: true,
      width: 100,
      align: 'center',
    },
    {
      title: '学历',
      dataIndex: 'education',
      valueType: 'select',
      width: 80,
      align: 'center',
      valueEnum: {
        1: {
          text: '小学',
          status: '1',
        },
        2: {
          text: '初中',
          status: '2',
        },
        3: {
          text: '高中',
          status: '3',
        },
        4: {
          text: '大专',
          status: '4',
        },
        5: {
          text: '本科',
          status: '5',
        },
        6: {
          text: '研究生',
          status: '6',
        },
        7: {
          text: '博士',
          status: '7',
        },
      },
    },
    {
      title: '婚姻状况',
      dataIndex: 'marital_status',
      valueType: 'select',
      width: 80,
      align: 'center',
      valueEnum: {
        0: {
          text: '未婚',
          status: '0',
        },
        1: {
          text: '已婚',
          status: '1',
        },
      },
    },
    {
      title: '职位',
      dataIndex: 'position',
      align: 'center',
      width: 100,
    },
    {
      title: '政治面貌',
      dataIndex: 'political_outlook',
      align: 'center',
      width: 80,
    },
    {
      title: '人员类别',
      dataIndex: 'personnel_type',
      align: 'center',
      width: 150,
    },
    {
      title: '入职时间',
      dataIndex: 'entry_time',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            'entry_time[0]': value[0],
            'entry_time[1]': value[1],
          };
        },
      },
    },
    {
      title: '入职时间',
      dataIndex: 'entry_time',
      valueType: 'date',
      sorter: true,
      hideInSearch: true,
      width: 100,
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueType: 'select',
      valueEnum: {
        0: {
          text: '禁用',
          status: '0',
        },
        1: {
          text: '启用',
          status: '1',
        },
      },
      hideInTable: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      width: 100,
      align: 'center',
      render: (text, record) => [
        <Switch
          key={record.id + record.status}
          checkedChildren="启用"
          unCheckedChildren="禁用"
          defaultChecked={record.status === 1 ? true : false}
          onChange={async (checked: boolean) => {
            const res = await setStatus(record.id, { status: checked ? 1 : 0 });
            if (res.status === 20000) {
              message.success(res.message);
            } else {
              actionRef.current?.reload();
            }
          }}
        />,
      ],
    },

    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
      width: 180,
      align: 'center',
    },
    {
      title: '创建时间',
      key: 'created_at',
      dataIndex: 'created_at',
      valueType: 'dateTimeRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            'created_at[0]': value[0],
            'created_at[1]': value[1],
          };
        },
      },
    },
    {
      title: '更新时间',
      key: 'updated_at',
      dataIndex: 'updated_at',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
      width: 180,
      align: 'center',
    },
    {
      title: '更新时间',
      key: 'updated_at',
      dataIndex: 'updated_at',
      valueType: 'dateTimeRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            updated_at: value,
          };
        },
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 200,
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      render: (_, row) => [
        <FormIndex
          id={row.id}
          key={row.id}
          onConfirm={() => {
            return actionRef.current?.reload();
          }}
        />,
        <CDel
          key={row.id}
          onCancel={async () => {
            const res = await del(row.id);
            if (res.status === 20000) {
              message.success(res.message);
              actionRef.current?.reload();
            }
          }}
        />,
      ],
    },
  ];
  return (
    <PageContainer fixedHeader={true} title={false}>
      <ProTable
        scroll={{ x: 1300 }}
        actionRef={actionRef}
        rowKey="id"
        columns={columns}
        request={async (params: API.ListQequest, sort) => {
          const data = await getSort(params, sort);
          const res = await getList(data);
          return setLsetData(res);
        }}
        options={{ fullScreen: true }}
        rowSelection={{ fixed: true }}
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
        columnsState={{
          onChange: (map) => {
            maps = map;
          },
        }}
        tableAlertOptionRender={({ selectedRows, selectedRowKeys, onCleanSelected }) => {
          return (
            <Space size={16}>
              <CDelAll
                key={selectedRowKeys.length}
                count={selectedRowKeys.length}
                onCancel={async () => {
                  const res = await delAll({ idArr: selectedRowKeys });
                  if (res.status === 20000) {
                    message.success(res.message);
                    actionRef.current?.reload();
                    onCleanSelected();
                  }
                }}
              />
              <a
                onClick={async () => {
                  const selectedRowsCope = JSON.parse(JSON.stringify(selectedRows));
                  const sexList = ['女', '男'];
                  const maritalStatusList = ['未婚', '已婚'];
                  const educationList = ['小学', '初中', '高中', '大专', '本科', '研究生', '博士'];
                  selectedRowsCope.map((item: any) => {
                    item.department_to = item.department_to?.name || '';
                    item.sex = sexList[item.sex];
                    item.marital_status = maritalStatusList[item.marital_status];
                    item.education = educationList[item.education];
                  });
                  exportExcel({
                    fileName: '人员管理',
                    columns,
                    maps,
                    selectedRows: selectedRowsCope,
                  });
                }}
              >
                导出数据
              </a>
            </Space>
          );
        }}
        headerTitle={
          <FormIndex
            onConfirm={() => {
              return actionRef.current?.reload();
            }}
          />
        }
      />
    </PageContainer>
  );
};
export default Index;
